<?php

namespace Kangcg\WeChat\Behavior;

use Kangcg\Application\Base\Behavior;
use Kangcg\Application\Base\Event;
use Kangcg\Application\Cache\FileCache;
use Kangcg\WeChat\Library\WeChatTrait;

class WeChatBehavior extends Behavior
{
    public function events()
    {
        return [
            WeChatTrait::EVENT_BEFORE_REFRESH_ACCESS_TOKEN => [$this, 'beforeRefreshAccessToken'],
            WeChatTrait::EVENT_AFTER_REFRESH_ACCESS_TOKEN => [$this, 'afterRefreshAccessToken'],

            WeChatTrait::EVENT_BEFORE_REFRESH_COMPONENT_TOKEN => [$this, 'beforeRefreshComponentToken'],
            WeChatTrait::EVENT_AFTER_REFRESH_COMPONENT_TOKEN => [$this, 'afterRefreshComponentToken'],

            WeChatTrait::EVENT_ACCESS_TOKEN_ERROR => [$this, 'errorAccessToken'],
            WeChatTrait::EVENT_lOG => [$this, 'log'],

            WeChatTrait::EVENT_BEFORE_REFRESH_AUTHORIZER_ACCESS_TOKEN => [$this, 'beforeRefreshAuthorizerToken'],
        ];
    }

    /**
     * 监听AccessToken42001错误
     * @param Event $event
     */
    public function errorAccessToken(Event $event)
    {
        $event->sender->cache->set($event->sender->getAccessTokenCacheKey(), null);
    }

    /**
     * 监听AccessToken更新之前事件
     * @param Event $event
     */
    public function beforeRefreshAccessToken(Event $event)
    {
        if ($event->data['access_token'] = $event->sender->cache->get($event->sender->getAccessTokenCacheKey())) {
            $event->handled = true;
        }
    }

    /**
     * 监听AccessToken更新之后事件
     * @param Event $event
     */
    public function afterRefreshAccessToken(Event $event)
    {
        if (!empty($event->data['access_token'])) {
            $event->sender->cache->set($event->sender->getAccessTokenCacheKey(), $event->data['access_token'], 7150);
        }
    }

    /**
     * 第三方平台的access_token刷新之前
     * @param Event $event
     */
    public function beforeRefreshComponentToken(Event $event)
    {
        if ($event->data['component_access_token'] = $event->sender->cache->get($event->sender->component_appid . $event->sender->component_appsecret)) {
            $event->handled = true;
        }
    }

    /**
     * 第三方平台的access_token刷新之后
     * @param Event $event
     */
    public function afterRefreshComponentToken(Event $event)
    {
        if (!empty($event->data['component_access_token'])) {
            $event->sender->cache->set($event->sender->component_appid . $event->sender->component_appsecret, $event->data['component_access_token'], 7150);
        }
    }

    /**
     * 日志事件
     * @param Event $event
     */
    public function log(Event $event)
    {

    }

    private function getLogsPath()
    {
        return __DIR__ . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR;
    }
}
